package cn.yj.admin.frame.shiro;

import cn.yj.admin.entity.vo.MenuTree;
import cn.yj.admin.frame.shiro.reaml.ShiroRealm;
import cn.yj.admin.entity.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;
import java.util.List;

/**
 * <br>
 *
 * @author 永健
 * @since 2020-12-17 18:25
 */
public class ShiroUtils {
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static List<MenuTree> getUserMenu() {
        LoginUser currentUser = getCurrentUser();
        if (currentUser != null) {
            return currentUser.getUserMenu();
        }
        return new ArrayList<>();
    }

    public static <T> T getCurrentUser() {
        Subject subject;
        try {
            subject = SecurityUtils.getSubject();
            if (subject == null) {
                return null;
            }

            Object principal = subject.getPrincipal();
            if (principal == null) {
                return null;
            }
            return (T) principal;
        } catch (Exception e) {
            System.out.println("用户未登陆");
        }

        return null;
    }

    public static void clearCacheAuthorizationInfo() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm shiroRealm = (ShiroRealm) rsm.getRealms().iterator().next();
        shiroRealm.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    private static ShiroRealm getRealm() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        return (ShiroRealm) rsm.getRealms().iterator().next();
    }
}
